﻿using BCCommon;
using BCEntity.Common.FAQ;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace BCData.Common.FAQ
{
    public class FaqData : IFaqData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM faq";
        private const string QUERY = @"SELECT FaqId,Enabled,CreateTime,ReplyTime,ReplyEmail,AdminId,AdminFullName,Title,Question,Answer,KeyWord,IsShow,IsDelete,IsReply,IsSolve FROM faq";
        private const string querySql =
            @"SELECT A.FaqId, A.Title, A.Question, A.Answer, A.KeyWord, A.IsShow, A.IsDelete, A.IsReply, A.IsSolve,A.Enabled, A.CreateTime, A.ReplyTime, A.ReplyEmail, A.AdminId, A.AdminFullName 
                    FROM faq A ";

        public FaqData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }

        public IEnumerable<FAQEntity> QueryFAQ(long? faqId, string title, string keyWord, DateTime? start, DateTime? end, bool? ascending, bool fromSim, out int dataCount, int pageIndex = 1, int pageSize = 10)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();

            if (faqId.HasValue)
            {
                wheres.Add("A.FaqId=?FaqId");
                parameters.Add("?FaqId", faqId, DbType.Int64);
            }
            if (!string.IsNullOrWhiteSpace(title))
            {
                wheres.Add("A.Title=?Title");
                parameters.Add("?Title", title, DbType.AnsiString, size: 50);
            }
            if (!string.IsNullOrWhiteSpace(keyWord))
            {
                wheres.Add("A.KeyWord LIKE CONCAT('%',CONCAT(?KeyWord,'%'))");
                parameters.Add("?KeyWord", keyWord, DbType.AnsiString, size: 200);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("A.CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("A.CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("A.CreateTime>=?Start AND A.CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            if (!fromSim)
            {
                wheres.Add("A.IsDelete=0");
                wheres.Add("A.IsShow=1");
            }

            string sql = string.Format("{0} {1} ORDER BY CreateTime DESC LIMIT {2},{3};SELECT COUNT(1) FROM faq A {1}", querySql,
                wheres.Count > 0 ? "WHERE " + string.Join(" AND ", wheres) : string.Empty,
                (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                pageSize);

            var results = this.databaseContext.Slave.QueryMultiple<FAQEntity, int>(sql, parameters);
            dataCount = results.Item2;
            return results.Item1;
        }

        public FAQEntity NewAdd(string title, string question, string replyEmail)
        {
            DynamicParameters parameters = new DynamicParameters();
            string addSql =
                @"INSERT INTO faq (Title, Question, IsShow, IsDelete, IsReply, IsSolve, CreateTime, ReplyEmail) VALUES (?Title, ?Question, 0, 0, 0, 0, NOW(), ?ReplyEmail)";

            parameters.Add("?Title", title, DbType.AnsiString, size: 50);
            parameters.Add("?Question", question, DbType.AnsiString);
            parameters.Add("?ReplyEmail", replyEmail, DbType.AnsiString, size: 50);

            string sql = string.Format("{0};{1} WHERE FaqId=LAST_INSERT_ID()", addSql, querySql);
            var result = this.databaseContext.Master.QueryFirstOrDefault<FAQEntity>(sql, parameters, databaseContext.Transaction);
            return result;
        }

        public FAQEntity ModifyReply(long faqId, string answer, string keyWord, long adminId, string adminFullName)
        {
            DynamicParameters parameters = new DynamicParameters();
            string updateSql = @"UPDATE faq SET Answer=?Answer,KeyWord=?KeyWord,IsReply=1,IsSolve=1,ReplyTime=NOW(),AdminId=?AdminId,AdminFullName=?AdminFullName WHERE FaqId=?FaqId";
            parameters.Add("?Answer", answer, DbType.AnsiString);
            parameters.Add("?KeyWord", keyWord, DbType.AnsiString, size: 200);
            parameters.Add("?AdminId", adminId, DbType.Int64);
            parameters.Add("?AdminFullName", adminFullName, DbType.AnsiString, size: 20);
            parameters.Add("?FaqId", faqId, DbType.Int64);

            string sql = string.Format("{0};{1} WHERE FaqId=?FaqId", updateSql, querySql);
            var result = this.databaseContext.Master.QueryFirstOrDefault<FAQEntity>(sql, parameters, databaseContext.Transaction);
            return result;
        }

        public FAQEntity ModifyIsShow(long faqId,bool isShow)
        {
            DynamicParameters parameters = new DynamicParameters();
            string updateSql = @"UPDATE faq SET IsShow=?IsShow WHERE FaqId=?FaqId";
            parameters.Add("?FaqId",faqId,DbType.Int64);
            parameters.Add("?IsShow",isShow,DbType.Boolean);
            string sql = string.Format("{0};{1} WHERE FaqId=?FaqId", updateSql, querySql);
            var result = this.databaseContext.Master.QueryFirstOrDefault<FAQEntity>(sql, parameters, databaseContext.Transaction);
            return result;
        }

        public bool ModifyIsDelete(long faqId)
        {
            DynamicParameters parameters = new DynamicParameters();
            string updateSql = @"UPDATE faq SET IsDelete=1 WHERE FaqId=?FaqId";
            parameters.Add("?FaqId",faqId,DbType.Int64);
            object result = this.databaseContext.Master.ExecuteScalar(updateSql, parameters, databaseContext.Transaction);
            return result != null;
        }

        public IEnumerable<FAQEntity> QuerySpecify(int index,int amount)
        {
            string sql = string.Format("{0} WHERE IsShow=1 AND IsDelete=0 AND Enabled=1 ORDER BY CreateTime DESC LIMIT {1},{2}",querySql,index,amount);
            var results = this.databaseContext.Slave.QueryMultiple<FAQEntity, int>(sql);
            return results.Item1;
        }

        #region 检查常见问题ID是否存在
        public async Task<bool> Exists(long faqId)
        {
            string sql = string.Format(@"{0} WHERE FaqId=?FaqId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?FaqId", faqId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 启用常见问题ID
        public async Task<bool> Enabled(long faqId)
        {
            string sql = @"UPDATE faq SET Enabled=1 WHERE FaqId=?FaqId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?FaqId", faqId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 禁用常见问题ID
        public async Task<bool> Disabled(long faqId)
        {
            string sql = @"UPDATE faq SET Enabled=0 WHERE FaqId=?FaqId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?FaqId", faqId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion
    }
}
